<template>
  <span v-if="isVisible">{{timeText}}</span>
</template>

<script>
import { tool } from 'js/util'

export default {
  props: {
    start: [String, Date, Number],
    target: [String, Date, Number]
  },
  data() {
    return {
      isVisible: true,
      timer: null,
      timeText: ''
    }
  },
  mounted() {
    clearInterval(this.timer)
    const start = +new Date(this.start)
    const target = +new Date(this.target)
    let diff = (target - start) / 1000
    this.timeText = this._formatTime(diff)
    this.timer = setInterval(() => {
      diff -= 1
      this.timeText = this._formatTime(diff)
      if (diff <= 0) {
        clearInterval(this.timer)
        this.isVisible = false
        this.$emit('on-timer')
      }
    }, 1000)
  },
  methods: {
    // 时间戳转化为 天时分秒
    _formatTime(timestamp) {
      let time = parseInt(timestamp)
      let d, h, m, s
      if (time) {
        if (time < 60) {
          s = time
          time = `${s}秒`
        } else if (time > 60 && time < 3600) {
          m = parseInt(time / 60)
          s = parseInt(time % 60)
          time = `${m}分${s}秒`
        } else if (time >= 3600 && time < 86400) {
          h = parseInt(time / 3600)
          m = parseInt(time % 3600 / 60)
          s = parseInt(time % 3600 % 60 % 60)
          time = `${h}时${m}分${s}秒`
        } else if (time >= 86400) {
          d = parseInt(time / 86400)
          h = parseInt(time % 86400 / 3600)
          m = parseInt(time % 86400 % 3600 / 60)
          s = parseInt(time % 86400 % 3600 % 60 % 60)
          time = `${tool.addZero(d)}天${tool.addZero(h)}时${tool.addZero(m)}分${tool.addZero(s)}秒`
        }
      }
      return time
    }
  },
  destroyed() {
    clearInterval(this.timer)
  }
}
</script>